<template>
  <span>
    <template v-for="(part, index) in highlightedParts" :key="index">
      <span v-if="part.highlight" class="highlight">{{ part.text }}</span>
      <span v-else>{{ part.text }}</span>
    </template>
  </span>
</template>

<script setup>
import { computed } from 'vue'

const props = defineProps({
  text: {
    type: String,
    required: true
  },
  search: {
    type: String,
    required: true
  }
})

const highlightedParts = computed(() => {
  if (!props.search) return [{ text: props.text, highlight: false }]

  const reg = new RegExp(`(${props.search.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi')
  const parts = props.text.split(reg)

  return parts
    .map((part) => ({
      text: part,
      highlight: part.toLowerCase() === props.search.toLowerCase()
    }))
    .filter((part) => part.text.length > 0)
})
</script>

<style scoped>
.highlight {
  color: #00c25b;
}
</style>
